package com.zstax.demo.encrypt.util.sm3;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class SM3Util {
	/**
	 * 编码
	 */
	private static final String ENCODING = "UTF-8";
	/**
	 * sm3算法加密
	 *
	 * @param paramStr 待加密字符串
	 * @return 返回加密后，固定长度=32的16进制字符串
	 * @explain
	 */
	public static String encrypt(String paramStr) {
		// 将返回的hash值转换成16进制字符串
		String resultHexString = "";
		try {
			// 将字符串转换成byte数组
			byte[] srcData = paramStr.getBytes(ENCODING);
			// 调用hash()
			byte[] resultHash = hash(srcData);
			// 将返回的hash值转换成16进制字符串
			resultHexString = ByteUtils.toHexString(resultHash);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return resultHexString;
	}

	public static byte[] hash(byte[] srcData) {
		SM3Digest digest = new SM3Digest();
		digest.update(srcData, 0, srcData.length);
		byte[] hash = new byte[digest.getDigestSize()];
		digest.doFinal(hash, 0);
		return hash;
	}

	public static boolean verify(byte[] srcData, byte[] sm3Hash) {
		byte[] newHash = hash(srcData);
		return Arrays.equals(newHash, sm3Hash);
	}

	public static byte[] hmac(byte[] key, byte[] srcData) {
		KeyParameter keyParameter = new KeyParameter(key);
		SM3Digest digest = new SM3Digest();
		HMac mac = new HMac(digest);
		mac.init(keyParameter);
		mac.update(srcData, 0, srcData.length);
		byte[] result = new byte[mac.getMacSize()];
		mac.doFinal(result, 0);
		return result;
	}
}
